package com.jsnj33.pdaproject.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.device.ScanManager;
import android.device.scanner.configuration.PropertyID;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jsnj33.pdaproject.R;
import com.jsnj33.pdaproject.bean.BatchAndProductBean;
import com.jsnj33.pdaproject.bean.InOutBean;
import com.jsnj33.pdaproject.bean.MsgBean;
import com.jsnj33.pdaproject.constant.Constants;
import com.jsnj33.pdaproject.utils.LogUtils;
import com.jsnj33.pdaproject.utils.StringUtility;
import com.jsnj33.pdaproject.utils.StringUtils;
import com.jsnj33.pdaproject.utils.ToastUtil;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.List;
import java.util.Map;

public class InActivity extends AppCompatActivity {
    private final static String SCAN_ACTION = ScanManager.ACTION_DECODE;//default action

    private static final String TAG = "InOutActivity";
    private Vibrator mVibrator;
    private ScanManager mScanManager;
    private SoundPool soundpool = null;
    private int soundid;
    private boolean isScaning = false;
    private ImageView ivBack;
    private TextView tvGH;
    private TextView tvGoodNo;
    private TextView tvGoodName;
    private TextView etRemark;
    private TextView tvTitle;
    private Button btnRetryScan;
    private EditText etQTY;
    String oper_flag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_in);
        initView();
        oper_flag = getIntent().getStringExtra("oper_flag");

        mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
    }

    private void initView() {
        String title = getIntent().getStringExtra("title");
        ivBack = findViewById(R.id.ivBack);
        tvGoodNo = findViewById(R.id.tvGoodNo);
        tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText(title);
        tvGoodName = findViewById(R.id.tvGoodName);
        btnRetryScan = findViewById(R.id.btnRetryScan);
        tvGH = findViewById(R.id.tvGH);
        etRemark = findViewById(R.id.etRemark);
        etQTY = findViewById(R.id.etQTY);
        Button submit = findViewById(R.id.submit);
        submit.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        submitOrder();
                    }
                }
        );
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btnRetryScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvGoodNo.setText("");
                tvGoodName.setText("");
                etQTY.setText("");
                etRemark.setText("");
            }
        });
    }

    private BroadcastReceiver mScanReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            isScaning = false;
            soundpool.play(soundid, 1, 1, 0, 0, 1);
            mVibrator.vibrate(100);

            byte[] barcode = intent.getByteArrayExtra(ScanManager.DECODE_DATA_TAG);
            int barcodelen = intent.getIntExtra(ScanManager.BARCODE_LENGTH_TAG, 0);
            byte temp = intent.getByteExtra(ScanManager.BARCODE_TYPE_TAG, (byte) 0);
            String str = new String(barcode, 0, barcodelen);
            if (StringUtility.isEmpty(str)) {
                ToastUtil.showGravityToast(InActivity.this, "扫码失败！", Gravity.CENTER, 0, 0);
                return;
            }
            String sbs = str.substring(0, 2);
            Log.i(TAG, "onReceive: " + str);
            switch (sbs) {
                case "ht":
                    StringUtils.UrlEntity urlEntity = StringUtils.parse(str);
                    String prodNo = urlEntity.params.get("PRD_NO");//货品码
                    String batNo = urlEntity.params.get("BAT_NO");//批号
                    scanningProductName(prodNo);
                    tvGoodNo.setText(prodNo);
                    break;
                default:
                    tvGH.setText(str);
                    break;
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        initScan();
        IntentFilter filter = new IntentFilter();
        int[] idbuf = new int[]{PropertyID.WEDGE_INTENT_ACTION_NAME, PropertyID.WEDGE_INTENT_DATA_STRING_TAG};
        String[] value_buf = mScanManager.getParameterString(idbuf);
        if (value_buf != null && value_buf[0] != null && !value_buf[0].equals("")) {
            filter.addAction(value_buf[0]);
        } else {
            filter.addAction(SCAN_ACTION);
        }

        registerReceiver(mScanReceiver, filter);
    }

    private void initScan() {
        mScanManager = new ScanManager();
        mScanManager.openScanner();
        mScanManager.switchOutputMode(0);
        soundpool = new SoundPool(1, AudioManager.STREAM_NOTIFICATION, 100); // MODE_RINGTONE
        soundid = soundpool.load("/etc/Scan_new.ogg", 1);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScanManager != null) {
            mScanManager.stopDecode();
            isScaning = false;
        }
        unregisterReceiver(mScanReceiver);
    }

    private void scanningProductName(final String barcode) {

        boolean b = judgeString(barcode);
        if (b == true) {
            ToastUtil.showGravityToast(InActivity.this, "二维码不存在！！！", Gravity.CENTER, 0, 0);
            return;
        }

        String url = Constants.SCANNING_PRODUCT_NAME_JINKUGOODSINFO;
        final JSONObject map = new JSONObject();
        try {
            map.put("barcode", barcode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestParams requestParams = new RequestParams(url);
        requestParams.setBodyContent(map.toString());
        Log.d(TAG, "scanningProductName url=: " + url);
        requestParams.setAsJsonContent(true);
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                String str = new String(result.toString());
                Log.i(TAG, "onSuccess: " + str);
                InOutBean inOutBean = new Gson().fromJson(result.toString(), InOutBean.class);
                if (inOutBean.getRespCode() == "1") {
                    tvGoodName.setText(inOutBean.getRespData().getPRD_NAME() + "");
                } else {
                    ToastUtil.showLongToast(InActivity.this, "" + inOutBean.getRespMsg());
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showLongToast(InActivity.this, "网络异常");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }

    /**
     * 提交订单
     */
    private void submitOrder() {
        String url = Constants.SCANNING_PRODUCT_NAME_JINKU;
        if (TextUtils.isEmpty(tvGH.getText())) {
            ToastUtil.showLongToast(InActivity.this, "请扫描工号");
            return;
        }
        if (TextUtils.isEmpty(tvGoodNo.getText())) {
            ToastUtil.showLongToast(InActivity.this, "请扫描货品码");
            return;
        }
        if (TextUtils.isEmpty(etQTY.getText())) {
            ToastUtil.showLongToast(InActivity.this, "请输入数量");
            return;
        }

        final JSONObject map = new JSONObject();
        try {
            map.put("oper_flag", oper_flag);
            map.put("user_no", tvGH.getText().toString() + "");
            map.put("prd_no", tvGoodNo.getText().toString() + "");
            map.put("prd_name", tvGoodName.getText().toString() + "");
            map.put("prd_name", tvGoodName.getText().toString() + "");
            map.put("remark", etRemark.getText().toString() + "");
            map.put("qty", etQTY.getText().toString() + "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String gson = new Gson().toJson(map);
        Log.d(TAG, "submitOrder: " + gson);
        RequestParams requestParams = new RequestParams(url);
        requestParams.setBodyContent(map.toString());
        requestParams.setAsJsonContent(true);
        x.http().post(requestParams, new Callback.CommonCallback<JSONObject>() {
            @Override
            public void onSuccess(JSONObject result) {
                String str = new String(result.toString());
                Log.i(TAG, "onSuccess: " + str);
                String respCode = result.optString("respCode");
                String respMsg = result.optString("respMsg");
                if (respCode.equals("-1")) {
                    ToastUtil.showLongToast(InActivity.this
                            , respMsg);
                } else {
                    ToastUtil.showLongToast(InActivity.this
                            , "提交成功");
                    tvGoodNo.setText("");
                    tvGoodName.setText("");
                    etQTY.setText("");
                    etRemark.setText("");
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                ToastUtil.showLongToast(InActivity.this, "网络异常");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }


    /**
     * 判断必传参数中是否有null或者""。
     *
     * @param str
     * @return true:有  false:无
     */
    private boolean judgeString(String... str) {
        for (int i = 0; i < str.length; i++) {
            if (StringUtility.isEmpty(str[i])) {
                return true;
            }
        }
        return false;
    }
}

